package com.atguigu.srb.core.service.impl;

import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.results.ResultCodeEnum;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author Atguigu
 * @since 2022-10-24
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    RedisTemplate redisTemplate;
    //增删改： 将增删改数据的parentid对应的缓存删除
//    @CacheEvict
    //拼接key：  value::key
    @Cacheable(value = "srb:dicts" , key = "{#pid}") //配置一个缓存唯一的key
    @Override
    public List<Dict> getDictsByPid(String pid) {
        List<Dict> dicts = baseMapper.selectList(new LambdaQueryWrapper<Dict>()
                .eq(Dict::getParentId, pid));
        //给每一个dict设置hasChildren属性值 :前端判断是否有下一级数据 有前端会发起请求查询
        dicts.forEach(dict -> {
            //判断当前节点有没有下一级数据:使用自己的id查询下一级数据
            Integer count = baseMapper.selectCount(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getParentId, dict.getId()));
            if(count>0){//有下一级
                dict.setHasChildren(true);
            }
        });
        return dicts;
    }

    @Override
    public List<Dict> queryDictsByDictCode(String dictCode) {
        Dict dict = this.getOne(new LambdaQueryWrapper<Dict>()
                .eq(Dict::getDictCode, dictCode));
        if(dict==null){
            return null;
        }
        //根据dictcode查询下一级数据字典
        Long dictId = dict.getId();
        //使用dictId当做父id查询它的下一级数据字典
        List<Dict> dicts = this.getDictsByPid(dictId.toString());
        return dicts;
    }

    @Override
    public String queryDictNameByDictCodeAndValue(String dictCode, Integer value) {
        Dict dict = this.getOne(new LambdaQueryWrapper<Dict>()
                .select(Dict::getId)
                .eq(Dict::getDictCode, dictCode));
        //查询一级数据字典的id
        Long dictId = dict.getId();
        //查询二级数据字典的name
        Dict child = this.getOne(new LambdaQueryWrapper<Dict>()
                .select(Dict::getName)
                .eq(Dict::getParentId, dictId)
                .eq(Dict::getValue, value));
        return child.getName();
    }

}
